﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace CommandListPanel
{
    /// <summary>
    /// knowledgemapUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class knowledgemapUserControl : UserControl
    {
        public knowledgemapUserControl(JObject command)
        {
            InitializeComponent();
            jsonObject = command;
            LoadAndDisplayJsonData();
            ExpandAllNodes(jsonTreeView);

        }

        public JObject jsonObject;
        public object seletedJtoken = null;

        private void LoadAndDisplayJsonData()
        {
            //string jsonData = @"{
            //    ""string"": ""Hello, World!"",
            //    ""integer"": 42,
            //    ""float"": 3.14,
            //    ""boolean"": true,
            //    ""nullValue"": null,
            //    ""object"": {
            //        ""property1"": ""value1"",
            //        ""property2"": 123,
            //        ""nestedObject"": {
            //            ""nestedProperty"": ""nestedValue""
            //        }
            //    },
            //    ""array"": [
            //        ""item1"",
            //        ""item2"",
            //        {
            //            ""nestedObjectInArray"": {
            //                ""nestedPropertyInArray"": ""nestedValueInArray""
            //            }
            //        }
            //    ],
            //    ""date"": ""2023-12-09T10:30:00Z"",
            //    ""url"": ""https://www.example.com"",
            //    ""email"": ""user@example.com"",
            //    ""color"": ""#FF5733"",
            //    ""coordinates"": {
            //        ""latitude"": 40.7128,
            //        ""longitude"": -74.0060
            //    },
            //    ""currency"": {
            //        ""code"": ""USD"",
            //        ""amount"": 100.50
            //    },
            //    ""nestedArray"": [
            //        ""itemA"",
            //        42,
            //        false,
            //        null,
            //        {
            //            ""nestedProperty"": ""nestedValue""
            //        }
            //    ]
            //}";

            //jsonObject = JObject.Parse(jsonData);
            TreeViewItem rootNode = new TreeViewItem();
            rootNode.Header = "JSON Data";
            jsonTreeView.Items.Add(rootNode);

            DisplayJsonObject(jsonObject, rootNode);
        }

        private void DisplayJsonObject(JObject jsonObject, TreeViewItem parentNode)
        {
            foreach (var property in jsonObject.Properties())
            {
                TreeViewItem propertyNode = new TreeViewItem();
                propertyNode.Header = property.Name;
                parentNode.Items.Add(propertyNode);

                if (property.Value is JObject)
                {
                    DisplayJsonObject((JObject)property.Value, propertyNode);
                }
                else if (property.Value is JArray)
                {
                    DisplayJsonArray((JArray)property.Value, propertyNode);
                }
                else
                {

                    TreeViewItem valueNode = new TreeViewItem();                 
                    valueNode.Header = property.Value.ToString();
                    valueNode.MouseDoubleClick += (sender, e) => { seletedJtoken = property; };
                    valueNode.MouseDoubleClick += ValueNode_MouseDoubleClick;
                    // 设置边框属性
                    valueNode.BorderBrush = Brushes.Black;
                    valueNode.BorderThickness = new Thickness(1);



                    // 设置内容的最小宽度
                    Border contentBorder = new Border();
                    contentBorder.MinWidth = 30;

                    TextBlock textBlock = new TextBlock();
                    textBlock.Text = property.Value.ToString();

                    contentBorder.Child = textBlock;
                    valueNode.Header = contentBorder;


                    propertyNode.Items.Add(valueNode);
                }
            }
        }


        private void DisplayJsonArray(JArray jsonArray, TreeViewItem parentNode)
        {
            int i = 0;
            foreach (var item in jsonArray)
            {

                TreeViewItem itemNode = new TreeViewItem();
                itemNode.Header = "[" + i + "]";
                parentNode.Items.Add(itemNode);

                if (item is JObject)
                {
                    DisplayJsonObject((JObject)item, itemNode);
                }
                else if (item is JArray)
                {
                    DisplayJsonArray((JArray)item, itemNode);
                }
                else
                {
                    TreeViewItem valueNode = new TreeViewItem();
                    valueNode.Header = item.ToString();
                    //双击可以开始编辑修改，并且lostfocus后保存
                    valueNode.MouseDoubleClick += (sender, e) => { seletedJtoken = item; };
                    valueNode.MouseDoubleClick += ValueNode_MouseDoubleClick;


                    // 设置边框属性
                    valueNode.BorderBrush = Brushes.Black;
                    valueNode.BorderThickness = new Thickness(1);


                    // 设置内容的最小宽度
                    Border contentBorder = new Border();
                    contentBorder.MinWidth = 30;
                    TextBlock textBlock = new TextBlock();
                    textBlock.Text = item.ToString();
                    contentBorder.Child = textBlock;
                    valueNode.Header = contentBorder;


                    itemNode.Items.Add(valueNode);
                }
                i++;
            }
        }


        private void ValueNode_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {


            TreeViewItem valueNode = (TreeViewItem)sender;

            Console.WriteLine(valueNode.Tag);

            //valueNode.Header是一个Border，border里面有一个texblock控件我需要对textblock控件进行双向修改
            TextBlock textBlock = (TextBlock)(valueNode.Header as Border).Child;
            // 获取原始文本
            string originalText = textBlock.Text;

            // 创建可编辑文本框
            TextBox editTextBox = new TextBox();
            editTextBox.MinWidth = 30;
            editTextBox.Text = originalText;
            editTextBox.PreviewKeyDown += EditTextBox_PreviewKeyDown;
            editTextBox.LostFocus += EditTextBox_LostFocus;

            // 替换节点内容为编辑框
            valueNode.Header = editTextBox;

            // 让编辑框获取焦点

            // 使用 Dispatcher 设置焦点
            // 使用 Dispatcher 设置焦点
            Dispatcher.BeginInvoke((Action)(() =>
            {
                editTextBox.Focus();
                Keyboard.Focus(editTextBox); // 试试添加这一行
                editTextBox.SelectAll();
            }), DispatcherPriority.Render);
        }

        /// <summary>
        /// 丢失光标的时候，也默认保存编辑结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox editTextBox = (TextBox)sender;
            TreeViewItem valueNode = (TreeViewItem)editTextBox.Parent;
            if (valueNode==null)
            {
                return;
            }
            // 获取编辑后的值
            string newValue = editTextBox.Text;


            Console.WriteLine(newValue);
            // 更新 JSON 数据模型
            UpdateJsonValue(valueNode.Parent as TreeViewItem, newValue);

            // 恢复节点内容为新的值
            //valueNode.Header = newValue;


            Border contentBorder = new Border();
            contentBorder.MinWidth = 30;
            TextBlock textBlock = new TextBlock();
            textBlock.Text = newValue;
            contentBorder.Child = textBlock;
            valueNode.Header = contentBorder;
        }


       
        /// <summary>
        /// 按下enter键的时候默认保存编辑器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void EditTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                TextBox editTextBox = (TextBox)sender;
                TreeViewItem valueNode = (TreeViewItem)editTextBox.Parent;

                // 获取编辑后的值
                string newValue = editTextBox.Text;


                Console.WriteLine(newValue);
                // 更新 JSON 数据模型
                UpdateJsonValue(valueNode.Parent as TreeViewItem, newValue);

                // 恢复节点内容为新的值
                //valueNode.Header = newValue;


                Border contentBorder = new Border();
                contentBorder.MinWidth = 30;
                TextBlock textBlock = new TextBlock();
                textBlock.Text = newValue;
                contentBorder.Child = textBlock;
                valueNode.Header = contentBorder;


            }
        }

        private void UpdateJsonValue(TreeViewItem treeViewItem, string newValue)
        {
            //根据对应关系，找到对应的jsonObject

            //seletedJtoken的类型
            Console.WriteLine(seletedJtoken.GetType());
            Console.WriteLine(seletedJtoken);
            if (seletedJtoken.GetType()==typeof(JProperty))
            {
                Console.WriteLine(666);
                JProperty jProperty = (JProperty)seletedJtoken;
                jProperty.Value = newValue;
            }
            else
            {
                Console.WriteLine(777);
                JValue jValue = (JValue)seletedJtoken;
                jValue.Value = newValue;
            }
            Console.WriteLine(jsonObject);
        }


        private void ExpandAllNodes(ItemsControl itemsControl)
        {
            foreach (var item in itemsControl.Items)
            {
                if (item is TreeViewItem treeViewItem)
                {
                    treeViewItem.IsExpanded = true;
                    ExpandAllNodes(treeViewItem);
                }
            }
        }




    }
}
